package com.grapevine.contact.db;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.grapevine.contact.data.ContactData;
import com.grapevine.contact.data.ItemData;
import com.grapevine.contact.util.Util;

public class DBHelper extends DbConfig implements ContactTable, GroupTable, ItemTable
{

	private DataBase help;
	private SQLiteDatabase mDb;
	private Context mContext;

	public DBHelper(Context c)
	{
		this.mContext = c;
		open();
	}

	private class DataBase extends SQLiteOpenHelper
	{

		public DataBase(Context context)
		{
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL(CREATE_CONTACTS_TABLE);
			db.execSQL(CREATE_GROUP_TABLE);
			db.execSQL(CREATE_ITEM_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			db.execSQL("DROP TABLE IF EXISTS " + GroupTable.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + ContactTable.TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + ItemTable.TABLE_NAME);
			onCreate(db);
		}
	}

	public DBHelper open() throws SQLiteException
	{
		help = new DataBase(mContext);
		mDb = help.getWritableDatabase();
		return this;
	}

	public void close()
	{
		mDb.close();
		help.close();
	}

	public void execute(String sql)
	{
		mDb.execSQL(sql);
	}

	/**
	 * 清理表数据
	 * 
	 * @param tableName
	 *            清理表数据
	 */
	public void clearTableData(String tableName)
	{

		execute("delete from " + tableName);
	}

	/**
	 * 创建分组
	 * 
	 * @param groupName
	 *            分组名字
	 * @param comment
	 *            分组备注
	 * @return 分组uuid
	 */
	public String createGroup(String groupName, String comment, String userIdentify)
	{
		String uuid = Util.createNewUUID();
		ContentValues values = new ContentValues();
		values.put(GROUP_NAME, groupName);
		values.put(GROUP_UUID, uuid);
		values.put(GroupTable.USER_IDENTITY, userIdentify);
		values.put(CREATE_TIME, String.valueOf(System.currentTimeMillis()));
		values.put(GROUP_COMMENT, comment);
		mDb.insert(GroupTable.TABLE_NAME, null, values);
		return uuid;
	}

	/**
	 * 创建新群组
	 * 
	 * @param groupName
	 *            分组名字
	 * @return 分区uuid
	 */
	public String createGroup(String groupName, String userIdentify)
	{
		return createGroup(groupName, "", userIdentify);
	}

	private void close(Cursor c)
	{
		if (null != c)
		{
			c.close();
			c = null;
		}
	}

	private String TAG = getClass().getSimpleName();

	public void insertContactDataFromLocalPhone(List<ContactData> list, String userIdentify)
	{
		if (null == list || 0 == list.size())
			return;
		for (ContactData data : list)
		{
			long id = data.getPhoneId();
			if (exist(id))
			{
				Log.e(TAG, "update item");
			}
			else
			{
				Log.e(TAG, "insert item");
				insert(data, userIdentify);
			}
		}

	}

	public void insertContactDataFromService(List<ContactData> list)
	{
		if (null == list || 0 == list.size())
			return;

	}

	public void insert(ContactData data, String userIdentify)
	{
		ContentValues values = new ContentValues();
		values.put(ContactTable.UUID, data.getUuid());
		values.put(ContactTable.GROUP_UUID, data.getGuuid());
		values.put(ContactTable.LASTMODIFIED, data.getLastModified());
		values.put(ContactTable.NAME, data.getName());
		values.put(ContactTable.LOCAL_PHONE_ID, data.getPhoneId());
		values.put(ContactTable.USER_IDENTITY, userIdentify);
		mDb.insert(ContactTable.TABLE_NAME, null, values);
		for (ItemData itemData : data.getItemDatas())
		{
			insert(itemData);
		}
	}

	public void insert(ItemData itemData)
	{
		ContentValues values = new ContentValues();
		values.put(ItemTable.FATHER_TYPE, itemData.getFatherType());
		values.put(ItemTable.TYPE, itemData.getType());
		values.put(ItemTable.LABLE, itemData.getLable());
		values.put(ItemTable.VALUE, itemData.getValue());
		values.put(ItemTable.UUID, itemData.getUuid());
		values.put(ItemTable.PERSON_UUID, itemData.getPUuid());
		values.put(ItemTable.LASTMODIFIED, itemData.getLastmodified());
		mDb.insert(ItemTable.TABLE_NAME, null, values);
	}

	/**
	 * 
	 * @param id
	 * @return 存在返回true
	 */
	public boolean exist(long id)
	{
		Cursor cursor = mDb.query(ContactTable.TABLE_NAME, null, LOCAL_PHONE_ID + " = " + id, null, null, null, null);
		boolean ret = cursor.getCount() > 0 ? true : false;
		close(cursor);
		return ret;
	}

	public Cursor getCursor(String tableName, String where)
	{
		return mDb.query(tableName, null, where, null, null, null, ContactTable.NAME + " asc");
	}

	public ContactData getContact(String uuid, String userIdentify)
	{

		ContactData data = new ContactData();

		Cursor pc = mDb.query(ContactTable.TABLE_NAME, null, ContactTable.UUID + " = '" + uuid + "' and " + ContactTable.USER_IDENTITY + " = '"
				+ userIdentify + "'", null, null, null, null);

		pc.moveToFirst();

		data.setGuuid(pc.getString(pc.getColumnIndex(ContactTable.GROUP_UUID)));

		data.setPhoneId(pc.getInt(pc.getColumnIndex(ContactTable.LOCAL_PHONE_ID)));

		data.setUuid(uuid);

		data.setName(pc.getString(pc.getColumnIndex(ContactTable.NAME)));

		data.setLastModified(pc.getString(pc.getColumnIndex(ContactTable.LASTMODIFIED)));

		Cursor itemCurson = mDb.query(ItemTable.TABLE_NAME, null, ItemTable.PERSON_UUID + " = '" + uuid + "'", null, null, null, "type asc");

		if (itemCurson.moveToFirst())
		{
			do
			{
				ItemData itemData = new ItemData();
				itemData.setUuid(itemCurson.getString(itemCurson.getColumnIndex(ItemTable.UUID)));
				itemData.setPUuid(itemCurson.getString(itemCurson.getColumnIndex(ItemTable.PERSON_UUID)));
				itemData.setValue(itemCurson.getString(itemCurson.getColumnIndex(ItemTable.VALUE)));
				itemData.setLable(itemCurson.getString(itemCurson.getColumnIndex(ItemTable.LABLE)));
				itemData.setType(itemCurson.getInt(itemCurson.getColumnIndex(ItemTable.TYPE)));
				itemData.setFatherType(itemCurson.getInt(itemCurson.getColumnIndex(ItemTable.FATHER_TYPE)));
				itemData.setLastmodified(itemCurson.getString(itemCurson.getColumnIndex(ItemTable.LASTMODIFIED)));
				data.getItemDatas().add(itemData);
			}
			while (itemCurson.moveToNext());
		}
		close(itemCurson);
		close(pc);
		return data;
	}

	public List<ContactData> getContacts(String userIdentify)
	{
		List<ContactData> list = new ArrayList<ContactData>();

		Cursor pc = mDb.query(ContactTable.TABLE_NAME, null, null, null, null, null, null);
		if (pc.moveToFirst())
		{
			do
			{
				list.add(getContact(pc.getString(pc.getColumnIndex(ContactTable.UUID)), userIdentify));
			}
			while (pc.moveToNext());
		}
		close(pc);
		return list;
	}

	public boolean exist(String uuid)
	{
		Cursor cursor = mDb.query(ContactTable.TABLE_NAME, null, ContactTable.UUID + " = " + uuid, null, null, null, null);
		boolean ret = cursor.getCount() > 0 ? true : false;
		close(cursor);
		return ret;
	}

	public SQLiteDatabase getDb()
	{
		return mDb;
	}

	public void setDb(SQLiteDatabase db)
	{
		mDb = db;
	}
}